import IPoint from "../interface/IPoint"
import Line from "./Line";
import { GridSystem } from "../Index";
import { BlockType } from "../Constants";

class MyPolygon extends Line {

    points: IPoint[]  // 坐标点集合
    pattern: any;

    constructor(points: IPoint[] = []) {
        super(points);
        this.points = points
        this.class = BlockType.POLYGON;
        this.pattern = null;
        // this.loadTexture();
    }

    loadTexture() {
        let ctx = GridSystem.gls.ctx;
        var img = new Image();
        img.src = '/cd.png';
        img.onload = () => {
            this.pattern = ctx.createPattern(img, 'repeat');
        };
    }

    draw(points: IPoint[] = []): void {
        let ctx = GridSystem.gls.ctx;
        ctx.save();
        ctx.beginPath()
        ctx.moveTo(points[0].x, points[0].y)
        points.forEach((point, index) => {
            if (index != 0) {
                ctx.lineTo(point.x, point.y);
            }
        })
        ctx.lineWidth = this.lineWidth;
        ctx.strokeStyle = this.strokeStyle
        // if (this.segments && this.segments.length > 0) {
        //     ctx.setLineDash(this.segments);
        // }
        // ctx.lineDashOffset = this.lineDashOffset;
        // ctx.stroke();
        ctx.closePath();
        ctx.fillStyle = "rgba(217,247,190, .8)";
        if (this.pattern) {
            ctx.fillStyle = this.pattern;
        }
        ctx.fill()
        this.setStroke(points)
        ctx.restore();
        this.hasPointIn(GridSystem.gls.mouseMovePoint)
        this.setControlPoints(points);  // 设置控制点
        this.update(points);  // 更新原始点
    }

    setStroke(points: IPoint[]) {
        let ctx = GridSystem.gls.ctx;
        ctx.beginPath()
        ctx.moveTo(points[0].x, points[0].y)
        let newPoints = [...points, points[0]];
        newPoints.forEach((point, index) => {
            if (index != 0) {
                ctx.lineTo(point.x, point.y);
            }
        })
        ctx.stroke();
        ctx.closePath();
    }
    hasPointIn(point?: IPoint | null) {
        if (point) {
            let ctx = GridSystem.gls.ctx;
            this.isPointIn = ctx.isPointInPath(point.x, point.y) || ctx.isPointInPath(point.x - 2, point.y - 2) || ctx.isPointInPath(point.x + 2, point.y + 2)
                || ctx.isPointInPath(point.x + 2, point.y) || ctx.isPointInPath(point.x - 2, point.y) || ctx.isPointInPath(point.x, point.y + 2) || ctx.isPointInPath(point.x, point.y - 2);
        }
    }

}

export default MyPolygon;